package in.muton.edushare.components.messaging.api;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.components.messaging.util.Recipients;
import in.muton.edushare.wicket.models.CayenneList;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.model.IModel;

import com.edushare.common.dao.MessagesDAO;
import com.edushare.common.vo.Messages;
import com.edushare.common.vo.Users;

public abstract class Message {
	
	public static final Log log = LogFactory.getLog(Message.class);
	public Messages send() {
		log.debug("Sending to "+rcv);
		Messages messageVO = new MessagesDAO(EduShareSession.get().getSessionORMInterface())
			.createMessage(EduShareSession.get().getLoggedInUser(), 
			getMessage(), rcv.getObject(), privacy);

		log.debug("Sending message");
		if(userList != null){
			List<IModel<Users>> userModelList = userList.getObject();
			for(IModel<Users> u:userModelList){
				addditionalProcessing(u.getObject());
				messageVO.addToAllMessageRecipients(u.getObject());
			}
		}else if(rcv.getObject() instanceof Users){
			messageVO.addToAllMessageRecipients((Users)(rcv.getObject()));
			messageVO.addToAllMessageRecipients(EduShareSession.get().getLoggedInUser());
			addditionalProcessing((Users)(rcv.getObject()));
		}else{
			List<Users> uList= Recipients.getRecipients(rcv.getObject(), privacy);
			Users user = EduShareSession.get().getLoggedInUser();
			if(!uList.contains(user))
				uList.add(user);
			for(Users u:uList){
				addditionalProcessing(u);
				messageVO.addToAllMessageRecipients(u);
			}
		}
		(EduShareSession.get()).getSessionORMInterface().commitAllChanges();
		return messageVO;
	}

	protected abstract void addditionalProcessing(Users u);

	public Message setReciever(Object rcv) {
		log.debug("setReciever "+rcv);
		this.rcv = new CayenneModel<Object>(rcv);
		return this;
	}
	
	public Message setReciever(CayenneList<Users> userList){
		this.userList = userList;
		return this;
	}

	public Message setPrivacy(int privacy){
		this.privacy = privacy;
		return this;
	}
	
	
	protected abstract String getMessage();
	
	private int privacy = -1;
	private IModel<Object> rcv;
	private CayenneList<Users> userList = null;
}
